package com.atguigu.gmall.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.util.StringUtils;


public class Jsons {
    static ObjectMapper mapper = new ObjectMapper();

    public static String toStr(Object object) {

        try {
            String s = mapper.writeValueAsString(object);
            return s;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T toObj(String jsonStr, TypeReference<T> tr) {
        if (StringUtils.isEmpty(jsonStr)){
            return null;
        }
        T t = null;

        try {
            t = mapper.readValue(jsonStr, tr);
            return t;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T toObj(String jsonStr, Class<T> clz) {
        if (StringUtils.isEmpty(jsonStr)){
            return null;
        }
            T t = null;
        try {
            t = mapper.readValue(jsonStr, clz);
            return t;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
